package br.com.ffm.praticas.facade;

import java.sql.SQLException;

import br.com.ffm.praticas.bean.Contact;
import br.com.ffm.praticas.dao.ContactDAO;

public class ContactFACADE {
	
	private static ContactFACADE contactFacade;
	private static ContactDAO contactDAO;
	
	private ContactFACADE(){
		contactDAO = new ContactDAO(); 
	}
	
	/**
	 * Method that create and returns an unique instance of ContactFACADE
	 * @return An unique instance of ContactFACADE
	 */
	public ContactFACADE getInstance(){
		if(contactFacade == null){
			contactFacade = new ContactFACADE();
		}
		return contactFacade;
	}
	
	/**
	 * Method that test if the Contact exist
	 * @param contact The Contact to be tested
	 * @return If exist returns true, else returns false
	 * @throws SQLException 
	 */
	public boolean alreadyExist(Contact contact) throws SQLException{
		if(contact != null){
			Contact c = contactDAO.getContact(contact.getId());
			if (c != null)
				return true;
			else
				return false;
		}
		return false;
	}
	
	/**
	 * Method that add a Contact
	 * @param contact The Contact to be added
	 * @return If add returns true, else returns false
	 * @throws SQLException 
	 */
	public boolean insert(Contact contact) throws SQLException{
		if(contact != null && !this.alreadyExist(contact)){
			contactDAO.insert(contact);
		}
		return false;
	}
	
	/**
	 * Method that remove a Contact
	 * @param contact The Contact to be removed
	 * @return If remove returns true, else returns false
	 */
	public boolean delete(Contact contact){
		return contactDAO.delete(contact);
	}
	
	/**
	 * Method that search a Contact
	 * @param id The if of the Contact to be found
	 * @return If found returns the Contact, else return null
	 * @throws SQLException 
	 */
	public Contact getContact(int id) throws SQLException{
		return contactDAO.getContact(id);
	}
	
	/**
	 * Method that update the attributes of a Contact
	 * @param contact The Contact with the new attributes
	 * @return If update returns true, else returns false
	 */
	public boolean update(Contact contact){
		return contactDAO.update(contact);
	}
	
	/**
	 * Method that count the number of Contacts
	 * @return The number of Contacts
	 * @throws SQLException 
	 */
	public int count() throws SQLException{
		return contactDAO.getContacts().size();
	}

}
